package com.thkj.util;

import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

/** 
 * 读取配置文件工具类
 * @author ll 
 * @version 1.0.0, 
 * @since 2014-5-21  
 */
public class PropertiesUtils {
	
	private static Properties props = null;
	private static String PRO_PARAM_REG = "\\$\\{\\d+\\}"; //匹配配置文件内容变量${1}
	private static Pattern p = Pattern.compile(PRO_PARAM_REG);
	static{
		try {
			Resource resource = new ClassPathResource("/sys-config.properties");
			props = PropertiesLoaderUtils.loadProperties(resource);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String getProperty(String key){
		return props.getProperty(key);
	}
	
	public static String getProperty(String key, String defauleValue){
		return props.getProperty(key, defauleValue);
	}
	
	/**
	 * 匹配内容中的${1}值，params长度必须与${1}值个数相等，位置先后匹配
	 * @param key
	 * @param params
	 * @return 
	 * @exception 
	 * @author liliang
	 * @createDate 2014-5-21 下午10:47:42
	 * @since  1.0.0
	 */
	public static String getPropertySetParam(String key, String [] params){
		String val = props.getProperty(key);
		Matcher m = p.matcher(val);
		int count = 0;
		while (m.find()) {
			count++;
		}
		if (count != params.length) {
			return null;
		}
		for(int i = 0; i < params.length ; i++){
			val = val.replaceFirst(PRO_PARAM_REG, params[i]);
		}
		return val;
	}
	
	public static void main(String[] args) {
		System.out.println(PropertiesUtils.getPropertySetParam("notice.user.register", new String[]{"123456", "ddddddd"}));
	}
}
